# add library
library(stringr)


# string length
str_length(c("i", "like", "programming", NA))
## [1]  1  4 11 NA


# 填充长度为3
str_pad(c("a", "ab", "abc"), 3)
## 1] "  a" " ab" "abc"


# 截断长度为10
str_trunc("R for data science", 10)
## [1] "R for d..."


# 移除空格
str_trim(c("a  ", "b  ", "a b"))
## [1] "a"   "b"   "a b"


#  字符串合并
str_c("x", 1:3, sep="_")
## [1] "x_1" "x_2" "x_3"
str_c("x", 1:3, collapse="_")
## [1] "x1_x2_x3"
str_c("x", 1:3, seq="_", collapse="_")
## [1] "x1__x2__x3_"



# 字符串重复
str_dup(c("A", "B"), 3)
## [1] "AAA" "BBB"
str_dup(c("A", "B"), c(3,2))
## [1] "AAA" "BB"


# 字符串拆分
x <- "10,8,7"
str_list <- str_split(x, ",")
print(str_list)
class(str_list)
## [1] "10" "8"  "7"
str_matrix <- str_split_fixed(x, ",", 2)
print(str_matrix)
class(str_matrix)
##      [,1] [,2] 
## [1,] "10" "8,7"


# 格式化输出
name<-"Andy"
mobile<-"1821241414"
str_glue("姓名：{name}", " 手机号码：{mobile}", .sep="; ")
## 姓名：Andy;  手机号码：1821241414


# 字符串匹配
x <- c("banana", "apple", "pear")
str_detect(x, "p")
str_which(x, "p")
str_count(x, "p")
str_locate(x, "a$")


# 字符串内容提取
x <- c("1978-2000", "2011-2020-2099")
pat <- "\\d{4}" # 提取4个数字
str_extract(x, pat)
## [1] "1978" "2011"
str_match(x, pat)
##      [,1]  
## [1,] "1978"
## [2,] "2011"

str_extract_all(x, pat)
str_match_all(x, pat)

print(">>>>直接匹配>>>>>>>>>>>>>>>>")
x=c("CDK弱 (+)10%", "CDK(+)30%-", "CDK(-)0+", "CDK(++)60%*")
str_extract(x, "\\d*%")
print(">>>>直接匹配>>>>>>>>>>>>>>>>")
str_extract(x, "\\d+%?")

print(">>>>>>>>>>>>>>extract>>>>>>>>>>>>>>")
x=c("175.10.237.40(湖南-长沙)", "114.243.12.168(北京-北京)", "125.211.78.251(黑龙江-哈尔滨)")
str_extract(x, "\\(.*-")
# (?<=   左边标志的引导语法
# (?=    右边标志的引导语法
str_extract(x, "(?<=\\().*(?=-)")
str_extract(x, "^.*(?=\\()")